package com.hjx.server;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by houjinxin on 2017/3/8.
 */
public class Request {

    private static final Logger logger = LoggerFactory.getLogger(Request.class);
    private static final char[] BUFF = new char[2048];
    private InputStream in;
    // uri 统一资源限定符
    private String uri;
    // 请求方法
    private String method;
    // 请求协议
    private String protocol;
    // 协议版本
    private String version;

    public Request(InputStream in) {
        this.in = in;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    private void parseUri(String firstLine) {
        String[] parts= firstLine.split(" ");
        setMethod(parts[0]);
        setUri(parts[1]);
        String[] protocolAndVersion = parts[2].split("/");
        setProtocol(protocolAndVersion[0]);
        setVersion(protocolAndVersion[1]);
        logger.info("parsed result is {}", this.toString());
    }

    /**
     * 此处的解析要从请求流中获取请求的url以"/"开头
     * TODO: 获取请求方法, 请求协议
     */
    public void parse() {
        logger.info("request input stream parsing...");
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        try {
            //TODO: 坑一 读取输入流完成后阻塞，不知道如何解决
//            System.out.println("开始");
//            do {
//                allLine+=line;
//                System.out.println("读取中：" + allLine);
//            } while((line = br.readLine()) != null);

            String allLine = br.readLine();
            String[] lines = allLine.split("\\r\\n");
            parseUri(lines[0]);
        } catch (IOException e) {
            logger.error("request parse failed.", e);
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }

}
